<template>
  <div class="staff-management-container">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <h3><el-icon><Avatar /></el-icon> 店员管理</h3>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon> 添加店员
          </el-button>
        </div>
      </template>

      <!-- 搜索筛选区域 -->
      <div class="search-section">
        <el-form :model="searchForm" inline>
          <el-form-item label="姓名">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入店员姓名"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="部门">
            <el-select
              v-model="searchForm.department"
              placeholder="请选择部门"
              clearable
              style="width: 150px"
            >
              <el-option label="销售部" value="sales" />
              <el-option label="收银部" value="cashier" />
              <el-option label="仓库部" value="warehouse" />
              <el-option label="客服部" value="service" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 120px"
            >
              <el-option label="在职" value="active" />
              <el-option label="离职" value="inactive" />
              <el-option label="休假" value="leave" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon> 搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon> 重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table
        :data="filteredStaffList"
        v-loading="loading"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="员工编号" width="100" />
        <el-table-column label="头像" width="80">
          <template #default="{ row }">
            <el-avatar :src="row.avatar" :size="40">
              <el-icon><User /></el-icon>
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column prop="phone" label="手机号" width="130" />
        <el-table-column prop="department" label="部门" width="100">
          <template #default="{ row }">
            <el-tag :type="getDepartmentTagType(row.department)">
              {{ getDepartmentName(row.department) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="position" label="职位" width="120" />
        <el-table-column prop="hireDate" label="入职日期" width="120" />
        <el-table-column prop="salary" label="基本工资" width="100">
          <template #default="{ row }">
            ¥{{ formatNumber(row.salary) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="handleSchedule(row)"
            >
              排班
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalCount"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑店员对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="staffFormRef"
        :model="staffForm"
        :rules="staffRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="staffForm.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="员工编号" prop="id">
              <el-input
                v-model="staffForm.id"
                placeholder="请输入员工编号"
                :disabled="isEdit"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="staffForm.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="staffForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门" prop="department">
              <el-select
                v-model="staffForm.department"
                placeholder="请选择部门"
                style="width: 100%"
              >
                <el-option label="销售部" value="sales" />
                <el-option label="收银部" value="cashier" />
                <el-option label="仓库部" value="warehouse" />
                <el-option label="客服部" value="service" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-input v-model="staffForm.position" placeholder="请输入职位" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入职日期" prop="hireDate">
              <el-date-picker
                v-model="staffForm.hireDate"
                type="date"
                placeholder="选择入职日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="基本工资" prop="salary">
              <el-input-number
                v-model="staffForm.salary"
                :min="0"
                :step="100"
                placeholder="基本工资"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="staffForm.status"
                placeholder="请选择状态"
                style="width: 100%"
              >
                <el-option label="在职" value="active" />
                <el-option label="离职" value="inactive" />
                <el-option label="休假" value="leave" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限角色" prop="role">
              <el-select
                v-model="staffForm.role"
                placeholder="请选择权限角色"
                style="width: 100%"
              >
                <el-option label="店员" value="staff" />
                <el-option label="组长" value="leader" />
                <el-option label="主管" value="supervisor" />
                <el-option label="经理" value="manager" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="staffForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 排班管理对话框 -->
    <el-dialog
      v-model="scheduleDialogVisible"
      title="排班管理"
      width="800px"
    >
      <div class="schedule-header">
        <h4>{{ currentStaff?.name }} - 本周排班</h4>
        <el-date-picker
          v-model="scheduleWeek"
          type="week"
          placeholder="选择周次"
          format="YYYY 第 ww 周"
          value-format="YYYY-MM-DD"
        />
      </div>

      <el-table :data="scheduleData" border style="width: 100%">
        <el-table-column prop="day" label="日期" width="120" />
        <el-table-column prop="dayName" label="星期" width="80" />
        <el-table-column label="上班时间" width="150">
          <template #default="{ row, $index }">
            <el-time-picker
              v-model="row.startTime"
              placeholder="开始时间"
              format="HH:mm"
              value-format="HH:mm"
              style="width: 100%"
              @change="updateSchedule($index)"
            />
          </template>
        </el-table-column>
        <el-table-column label="下班时间" width="150">
          <template #default="{ row, $index }">
            <el-time-picker
              v-model="row.endTime"
              placeholder="结束时间"
              format="HH:mm"
              value-format="HH:mm"
              style="width: 100%"
              @change="updateSchedule($index)"
            />
          </template>
        </el-table-column>
        <el-table-column label="工作时长" width="100">
          <template #default="{ row }">
            {{ calculateWorkHours(row.startTime, row.endTime) }}小时
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template #default="{ row, $index }">
            <el-select
              v-model="row.status"
              placeholder="状态"
              style="width: 100%"
              @change="updateSchedule($index)"
            >
              <el-option label="正常班" value="normal" />
              <el-option label="休息" value="rest" />
              <el-option label="请假" value="leave" />
              <el-option label="加班" value="overtime" />
            </el-select>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="scheduleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveSchedule">保存排班</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Avatar,
  Plus,
  Search,
  Refresh,
  User
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const scheduleDialogVisible = ref(false)
const isEdit = ref(false)
const staffFormRef = ref()
const currentStaff = ref(null)
const scheduleWeek = ref('')

// 搜索表单
const searchForm = reactive({
  name: '',
  department: '',
  status: ''
})

// 店员表单
const staffForm = reactive({
  id: '',
  name: '',
  phone: '',
  email: '',
  department: '',
  position: '',
  hireDate: '',
  salary: 0,
  status: 'active',
  role: 'staff',
  remark: ''
})

// 表单验证规则
const staffRules = {
  id: [
    { required: true, message: '请输入员工编号', trigger: 'blur' },
    { pattern: /^[A-Z0-9]{6,10}$/, message: '员工编号格式不正确', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ],
  position: [
    { required: true, message: '请输入职位', trigger: 'blur' }
  ],
  hireDate: [
    { required: true, message: '请选择入职日期', trigger: 'change' }
  ],
  salary: [
    { required: true, message: '请输入基本工资', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  role: [
    { required: true, message: '请选择权限角色', trigger: 'change' }
  ]
}

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)
const selectedStaff = ref([])

// 模拟店员数据
const staffList = ref([
  {
    id: 'EMP001',
    name: '张小明',
    phone: '13800138001',
    email: 'zhangxm@example.com',
    department: 'sales',
    position: '销售员',
    hireDate: '2024-01-15',
    salary: 4500,
    status: 'active',
    role: 'staff',
    avatar: '',
    remark: '工作积极，销售业绩优秀'
  },
  {
    id: 'EMP002',
    name: '李小红',
    phone: '13800138002',
    email: 'lixh@example.com',
    department: 'cashier',
    position: '收银员',
    hireDate: '2024-02-01',
    salary: 4000,
    status: 'active',
    role: 'staff',
    avatar: '',
    remark: '收银准确，服务态度好'
  },
  {
    id: 'EMP003',
    name: '王大强',
    phone: '13800138003',
    email: 'wangdq@example.com',
    department: 'warehouse',
    position: '仓库管理员',
    hireDate: '2023-12-01',
    salary: 4800,
    status: 'active',
    role: 'leader',
    avatar: '',
    remark: '仓库管理经验丰富'
  },
  {
    id: 'EMP004',
    name: '赵小美',
    phone: '13800138004',
    email: 'zhaoxm@example.com',
    department: 'service',
    position: '客服专员',
    hireDate: '2024-03-10',
    salary: 4200,
    status: 'leave',
    role: 'staff',
    avatar: '',
    remark: '客户服务专业，沟通能力强'
  },
  {
    id: 'EMP005',
    name: '刘经理',
    phone: '13800138005',
    email: 'liujl@example.com',
    department: 'sales',
    position: '销售经理',
    hireDate: '2023-08-01',
    salary: 8000,
    status: 'active',
    role: 'manager',
    avatar: '',
    remark: '管理经验丰富，团队领导能力强'
  }
])

// 排班数据
const scheduleData = ref([
  { day: '2024-08-12', dayName: '周一', startTime: '09:00', endTime: '18:00', status: 'normal' },
  { day: '2024-08-13', dayName: '周二', startTime: '09:00', endTime: '18:00', status: 'normal' },
  { day: '2024-08-14', dayName: '周三', startTime: '09:00', endTime: '18:00', status: 'normal' },
  { day: '2024-08-15', dayName: '周四', startTime: '09:00', endTime: '18:00', status: 'normal' },
  { day: '2024-08-16', dayName: '周五', startTime: '09:00', endTime: '18:00', status: 'normal' },
  { day: '2024-08-17', dayName: '周六', startTime: '', endTime: '', status: 'rest' },
  { day: '2024-08-18', dayName: '周日', startTime: '', endTime: '', status: 'rest' }
])

// 计算属性
const filteredStaffList = computed(() => {
  let filtered = staffList.value
  
  if (searchForm.name) {
    filtered = filtered.filter(item => 
      item.name.toLowerCase().includes(searchForm.name.toLowerCase())
    )
  }
  
  if (searchForm.department) {
    filtered = filtered.filter(item => item.department === searchForm.department)
  }
  
  if (searchForm.status) {
    filtered = filtered.filter(item => item.status === searchForm.status)
  }
  
  totalCount.value = filtered.length
  
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filtered.slice(start, end)
})

const dialogTitle = computed(() => {
  return isEdit.value ? '编辑店员' : '添加店员'
})

// 方法
const handleAdd = () => {
  isEdit.value = false
  resetStaffForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(staffForm, { ...row })
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除店员 "${row.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = staffList.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      staffList.value.splice(index, 1)
      ElMessage.success('删除成功！')
    }
  } catch {
    // 用户取消删除
  }
}

const handleSchedule = (row) => {
  currentStaff.value = row
  scheduleDialogVisible.value = true
  // 初始化排班数据
  initScheduleData()
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    department: '',
    status: ''
  })
  currentPage.value = 1
}

const handleSubmit = async () => {
  try {
    await staffFormRef.value.validate()
    
    if (isEdit.value) {
      // 编辑
      const index = staffList.value.findIndex(item => item.id === staffForm.id)
      if (index > -1) {
        Object.assign(staffList.value[index], { ...staffForm })
        ElMessage.success('编辑成功！')
      }
    } else {
      // 添加
      const exists = staffList.value.some(item => item.id === staffForm.id)
      if (exists) {
        ElMessage.error('员工编号已存在！')
        return
      }
      
      staffList.value.push({ ...staffForm, avatar: '' })
      ElMessage.success('添加成功！')
    }
    
    dialogVisible.value = false
  } catch (error) {
    ElMessage.error('请检查表单信息是否正确')
  }
}

const handleDialogClose = () => {
  resetStaffForm()
}

const handleSelectionChange = (selection) => {
  selectedStaff.value = selection
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const resetStaffForm = () => {
  Object.assign(staffForm, {
    id: '',
    name: '',
    phone: '',
    email: '',
    department: '',
    position: '',
    hireDate: '',
    salary: 0,
    status: 'active',
    role: 'staff',
    remark: ''
  })
  
  if (staffFormRef.value) {
    staffFormRef.value.clearValidate()
  }
}

const initScheduleData = () => {
  // 初始化本周排班数据
  const today = new Date()
  const monday = new Date(today.setDate(today.getDate() - today.getDay() + 1))
  
  scheduleData.value = Array.from({ length: 7 }, (_, index) => {
    const date = new Date(monday)
    date.setDate(monday.getDate() + index)
    
    const dayNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    
    return {
      day: date.toISOString().split('T')[0],
      dayName: dayNames[date.getDay()],
      startTime: index < 5 ? '09:00' : '', // 工作日默认9点开始
      endTime: index < 5 ? '18:00' : '', // 工作日默认6点结束
      status: index < 5 ? 'normal' : 'rest' // 周末默认休息
    }
  })
}

const updateSchedule = (index) => {
  // 排班数据更新逻辑
  console.log('更新排班:', index, scheduleData.value[index])
}

const handleSaveSchedule = () => {
  ElMessage.success('排班保存成功！')
  scheduleDialogVisible.value = false
}

const calculateWorkHours = (startTime, endTime) => {
  if (!startTime || !endTime) return 0
  
  const start = new Date(`2024-01-01 ${startTime}`)
  const end = new Date(`2024-01-01 ${endTime}`)
  
  const diff = end.getTime() - start.getTime()
  return Math.round(diff / (1000 * 60 * 60) * 10) / 10
}

const getDepartmentName = (department) => {
  const map = {
    sales: '销售部',
    cashier: '收银部',
    warehouse: '仓库部',
    service: '客服部'
  }
  return map[department] || department
}

const getDepartmentTagType = (department) => {
  const map = {
    sales: 'success',
    cashier: 'warning',
    warehouse: 'info',
    service: 'primary'
  }
  return map[department] || ''
}

const getStatusName = (status) => {
  const map = {
    active: '在职',
    inactive: '离职',
    leave: '休假'
  }
  return map[status] || status
}

const getStatusTagType = (status) => {
  const map = {
    active: 'success',
    inactive: 'danger',
    leave: 'warning'
  }
  return map[status] || ''
}

const formatNumber = (num) => {
  return num.toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  console.log('店员管理页面已加载')
})
</script>

<style scoped>
.staff-management-container {
  padding: 20px;
}

.page-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #303133;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.schedule-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.schedule-header h4 {
  margin: 0;
  color: #303133;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .staff-management-container {
    padding: 10px;
  }
  
  .search-section {
    padding: 15px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .schedule-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
}

@media (max-width: 576px) {
  .el-table {
    font-size: 12px;
  }
  
  .el-button {
    padding: 5px 10px;
    font-size: 12px;
  }
}
</style>